package com.tech.dcyao.server;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tech.dcyao.Iservice.HttpService;
import com.tech.dcyao.bean.ResultBean;
import com.tech.dcyao.service.HttpClientService;
import com.tech.dcyao.utils.HttpClientWrapper;
import com.tech.dcyao.utils.Utils;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
class ConnectionThread extends Thread {
    private Socket socket;
    private SocketServer socketServer;
    private Connection connection;
    private boolean isRunning;
    private ObjectMapper mapper = new ObjectMapper();
    private HttpService httpService;
    public ConnectionThread(Socket socket, SocketServer socketServer) throws JsonProcessingException {
        this.socket = socket;
        this.socketServer = socketServer;
        connection = new Connection(socket);
        this.httpService = new HttpClientService() ;
        isRunning = true;
        // 获取数据 并且发送
        String url = "initGPIOController";
        // dateYMD and dateHMS
        // String json = "{\"user\": \"123\"}";
        HashMap<String, String> map = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        String dateYMD = now.getYear() + "-" + now.getMonthValue() + "-" + now.getDayOfMonth();
        String dateHMS = now.getHour() + ":" + now.getMinute() + ":" + now.getSecond();
        map.put("dateYMD", dateYMD);
        map.put("dateHMS", dateHMS);
        String json = mapper.writeValueAsString(map);
        String responseMessage = "";
        try {
            String result = this.httpService.sendPostRequest(url,json);
            log.info("result" + result);
            ResultBean resultBean = mapper.readValue(result, ResultBean.class);
            responseMessage = Utils.coverDataToHex(resultBean.getData());
            responseMessage += Utils.setHexArrayToBCC(responseMessage);
        } catch (IOException e) {
            log.error("Error sending HTTP POST request: {}", e.getMessage());
        }
        connection.println(responseMessage);
    }


    @Override
    public void run() {
        while(isRunning) {
            // Check whether the socket is closed.
            if (socket.isClosed()) {
                isRunning = false;
                break;
            }

            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(
                                            socket.getInputStream()));
                String rawMessage = reader.readLine();
                String messageFlag = rawMessage.substring(0, 4).toUpperCase();
                String message = rawMessage;

                // Check the message flag.
                switch (messageFlag) {
                case MessageFlag.pureMessage:
                    // Handle the message.
                    if (message != null) {
                        socketServer.getMessageHandler().onReceive(connection, message);
                    }
                    break;
                case MessageFlag.connectionClosed:
                    stopRunning();
                    break;
                default:
                    break;
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public boolean isRunning() {
        return isRunning;
    }
    
    public void stopRunning() {
        isRunning = false;
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}